
var express = require('express');
var fs = require('fs');
var path = require('path');
var router = express.Router();
const spatial_ref_sys = require('../config/spatial_ref_sys');


/* 首页 */
router.get('/', function (req, res, next) {
    res.render('index', { title: 'index' });
});

router.get('/transform', function (req, res, next) {
    res.render('transform', { title: 'transform' });
});



router.get('/readFile', function (req, res, next) {
    var filePath = req.query.filePath;
    fs.readFile(path.join(__dirname, '../' + filePath), { encoding: 'utf-8' }, function (err, bytesRead) {
        if (err) throw err;
        var data = JSON.parse(bytesRead);
        console.log("readFile success");
        res.send(data);
    });
});

router.post('/writeFile', function (req, res) {
    var data = req.body.insertSql;
    var dirpath = path.join(__dirname, '../testFile');
    //先判断文件夹是否存在，不存在，先创建
    if (!fs.existsSync(dirpath)) {
        fs.mkdirSync(dirpath);
    }
    writeFile();

    function writeFile() {
        fs.writeFile(path.join(__dirname, '../testFile/data.sql'), data, { encoding: 'utf-8' }, function (err) {
            if (err) throw err;
            console.log("Export Account Success!");
        });
    }

});

router.get('/createProj4TextObject',function(req, res) {
    const spatialSysArray = spatial_ref_sys;
    const spatialSysObj = {};
    spatialSysArray.forEach(sys => {
        spatialSysObj[sys.srid] = sys;
    });
    res.send(spatialSysObj);
})

module.exports = router;